package main 
import (
    "appengine"
    "appengine/datastore"
    "http"
    "fmt"
    "time"
    "template"

    )

type User struct {
    Username string
    Name  string
    Email string
    Street string
    State string
    Country string
    Date    datastore.Time
}

type Product struct {
    Productname string
    Desription string
    Condition string
    Category string
    Date    datastore.Time
}

func init() {

    http.HandleFunc("/", handleRoot)
    http.HandleFunc("/UserCreated",handleUserCreated)
    http.HandleFunc("/ProductCreated",ProductCreated)
    http.HandleFunc("/Groups",Groups)
}

func Groups(w http.ResponseWriter,r *http.Request) {
 
    t := template.New("some template") //create a new template
    t, _ = t.ParseFile("static/site/groups.html") //open and parse a template text file

    c := appengine.NewContext(r)
    q := datastore.NewQuery("Product").Order("Productname").Limit(2)
    products := make([]Product, 0, 2)

    if _, err := q.GetAll(c, &products); err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
        return
    }
    fmt.Println(products[0]);
    if err := t.Execute(w, products); err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
    }

}


func handleRoot(w http.ResponseWriter, r *http.Request) {
    // fmt.Fprintf(w, "Hello world!", nil)
    http.Redirect(w,r,"/static/site/index.html",http.StatusFound)

}


func ProductCreated(w http.ResponseWriter, r *http.Request) {
   
   c := appengine.NewContext(r)
   g := Product{
        Productname: r.FormValue("VProductname"),
        Desription: r.FormValue("VDesription"),
	Condition: r.FormValue("VCondition"),
	Category: r.FormValue("VCategory"),
        Date:    datastore.SecondsToTime(time.Seconds()),
    }

 _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Product", nil), &g)
    if err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
        return
    }

    fmt.Fprintf(w,"Product created",nil)
}


func handleUserCreated(w http.ResponseWriter, r *http.Request) {
   
   c := appengine.NewContext(r)
   g := User{
        Name: r.FormValue("VName"),
        Email: r.FormValue("VEmail"),
	Street: r.FormValue("VStreet"),
	State: r.FormValue("VState"),
	Country: r.FormValue("VCountry"),
        Date:    datastore.SecondsToTime(time.Seconds()),
    }

 _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "User", nil), &g)
    if err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
        return
    }

    fmt.Fprintf(w,"User created",nil)
}